/*********************************************************************************
 *      Copyright:  (C) 2024 ioter<ioter@gmail.com>
 *                  All rights reserved.
 *
 *       Filename:  c.c
 *    Description:  This file 
 *                 
 *        Version:  1.0.0(30/06/24)
 *         Author:  ioter <ioter@gmail.com>
 *      ChangeLog:  1, Release initial version on "30/06/24 22:55:28"
 *                 
 ********************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>

#define PROXY_PORT 8899
#define PROXY_HOST "127.0.0.1"
#define MESSAGE "This is a message from a regular client."

int main() {
    int sock;
    struct sockaddr_in proxy_addr;

    if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
        perror("Socket creation error");
        exit(EXIT_FAILURE);
    }
	printf("Socket created\n");

    proxy_addr.sin_family = AF_INET;
    proxy_addr.sin_port = htons(PROXY_PORT);
    if (inet_pton(AF_INET, PROXY_HOST, &proxy_addr.sin_addr) <= 0) {
        perror("Invalid address/Address not supported");
        exit(EXIT_FAILURE);
    }
	printf("Address converted\n");

    if (connect(sock, (struct sockaddr *)&proxy_addr, sizeof(proxy_addr)) < 0) {
        perror("Connection to proxy failed");
        close(sock);
		exit(EXIT_FAILURE);
    }
	printf("Connected to proxy\n");

    if(send(sock, MESSAGE, strlen(MESSAGE), 0) < 0)
	{
		perror("Send failed");
        close(sock);
        exit(EXIT_FAILURE);
	}
	printf("Message sent: %s\n", MESSAGE);

    char buffer[1024] = {0};
    int bytes = read(sock, buffer, sizeof(buffer));
    if (bytes > 0) {
        buffer[bytes] = 0;
        printf("Received from proxy: %s\n", buffer);
    }
	else if(bytes < 0)
	{
		perror("Read failed");
	}
	else
	{
		printf("No message received from proxy\n");
	}

	while(1)
    {
        printf("enter msg: ");
		fgets(buffer, sizeof(buffer), stdin);
		buffer[strcspn(buffer, "\n")] = 0;
    
		if(strlen(buffer) == 0)
        {
            break;
        }

		if(send(sock, buffer, strlen(buffer), 0) < 0)
		{
			perror("Send failed");
            break;
		}

		bytes = read(sock, buffer, sizeof(buffer));
		if(bytes > 0)
		{
			buffer[bytes] = '\0';
            printf("Received from proxy: %s\n", buffer);
		}
		else if(bytes < 0) 
		{
			perror("Read failed");
		}
		else
		{
			printf("No message received from proxy\n");
		}
	}

    close(sock);

    return 0;
}
